﻿using Microsoft.IdentityModel.Tokens;
using WoodAdmin.Models;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace WoodAdmin.Common.Helper
{
    public class JwTHelper
    {
        // 密钥，注意不能太短
        public static string SecretKey { get; set; } = "d1ecd23c-dfdb-4005-a2ea-0fea210c858a";
        /// <summary>
        /// 生成JWT字符串
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public static string GetJWT(UserInfo userInfo)
        {
            //创建用户身份标识，可按需添加更多信息
            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()),
                new Claim("userid",userInfo.UserID.ToString()),
                new Claim("eamil",userInfo.Email),
            };

            // 创建令牌
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            JwtSecurityToken jwt = new JwtSecurityToken(
                issuer: "jwtIssuer2020",
                audience: "jwtAudience2020",
                signingCredentials: creds,
                claims: claims,// 声明的集合
                notBefore:DateTime.Now,
                expires: DateTime.Now.AddSeconds(1800) // token的有效时间
            );
            // 生成 jwt字符串
            var strJWT = new JwtSecurityTokenHandler().WriteToken(jwt);
            return strJWT;
        }
    }
}
